package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.JwtUtil;
import com.hmdp.utils.RSAUtils;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.io.UnsupportedEncodingException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.INVALID_JWT_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_CODE_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_CODE_TTL;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;
import static com.hmdp.utils.RedisConstants.USER_SIGN_KEY;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lxh
 * @since 2022-07-09
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            //2.不符合，返回错误信息
            return Result.fail("手机号格式错误！");
        }
        //3.符合，生成验证码
        String code = RandomUtil.randomNumbers(6);
        //4.保存验证码到session
        //session.setAttribute("code",code);
        //4.保存验证码到redis,两分钟内有效
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //5.发送验证码(模拟发送，真实情况下要使用阿里云等第三方平台)
        log.debug("发送短信验证码成功，验证码：{}",code);
        //返回ok
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) throws Exception {
        //1.校验手机号
        String phone=loginForm.getPhone();
        if(RegexUtils.isPhoneInvalid(phone)){
            //2.不符合，返回错误信息
            return Result.fail("手机号格式错误！");
        }
        String password = loginForm.getPassword();
        User user=new User();
        if(password!=null) {
            if(StrUtil.isEmpty(password)){
                //3.未输入密码
                return Result.fail("未输入密码！");
            }
            //4.一致，根据手机号查询用户
            user = query().eq("phone", phone).one();
            //5.判断用户是否存在
            if(user==null){
                log.debug("用户不存在");
                //6.不存在，创建用户并保存
                return Result.fail("用户不存在");
            }
            Map<String, String> keyMap = RSAUtils.getKeyMap();
            String privateKey = keyMap.get("privateKey");
            String publicKey = keyMap.get("publicKey");
            //模拟前端公钥加密
            String passwordEn = RSAUtils.encrypt(password, publicKey);
            //后端对前端发送的密文使用私钥解密
            String passwordDe = RSAUtils.decrypt(passwordEn, privateKey);
            String passwordMd5 = DigestUtil.md5Hex(passwordDe);
            //根据电话以及密码MD5查询数据库
            user = query().eq("phone", phone).eq("password", passwordMd5).one();
            if(user==null){
                log.info("密码错误");
                return Result.fail("密码错误");
            }
        }else {
            //2. 从redis获取验证码校验验证码
            String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
            String code = loginForm.getCode();
            if (code == null || !cacheCode.equals(code)) {
                //3.不一致，报错
                return Result.fail("验证码错误！");
            }
            //4.一致，根据手机号查询用户
            user = query().eq("phone", phone).one();
            //5.判断用户是否存在
            if (user == null) {
                log.debug("用户不存在");
                //6.不存在，创建用户并保存
                user = createUserWithPhone(phone);
            }
        }
/*        //7.保存用户信息到redis中
        //7.1 随机生成token,作为登陆令牌
        String token = UUID.randomUUID().toString(true);
        //7.2 将User对象转为HashMap存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString()));
        //7.3 存储,并设置有效期
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY+token,userMap);
        //7.4 设置token有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY+token,LOGIN_USER_TTL,TimeUnit.MINUTES);*/
        //8. 返回token

        //7.根据用户生成Jwt
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        String jwt = JwtUtil.jwtEncode(userDTO, LOGIN_USER_TTL);
        log.debug("jwt:{}",jwt);
        return Result.ok(jwt);
    }

    @Override
    public Result sign() {
        //1.获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        //2.获取日期
        LocalDate date = LocalDate.now();
        //3.拼接key
        String keySuffix = date.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key=USER_SIGN_KEY+userId+keySuffix;
        //4.获取今天是本月的第几天
        int dayOfMonth = date.getDayOfMonth();
        //5.写入redis setbit key offset 1
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth-1,true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //1.获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        //2.获取日期
        LocalDate date = LocalDate.now();
        //3.拼接key
        String keySuffix = date.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key=USER_SIGN_KEY+userId+keySuffix;
        //4.获取今天是本月的第几天
        int dayOfMonth = date.getDayOfMonth();
        //5.获取本月截止今天的所有签到记录,返回的是一个十进制的数字 bitfield key get u? 0 (u? 表示无符号多少位)
        List<Long> result = stringRedisTemplate.opsForValue().bitField(USER_SIGN_KEY + userId + keySuffix,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if(result==null||result.isEmpty()){
            //没有任何签到记录
            return Result.ok(0);
        }
        Long num = result.get(0);
        if(num==null || num==0){
            return Result.ok(0);
        }
        int count=0;
        //6.循环遍历
        while (true) {
            //6.1 与1做与运算,这样得到数字的最后一个bit位
            // 判断这个bit位是否为0，为0结束，为1 计数器加一
           if(( num & 1) == 0){
                break;
           }else{
               count++;
               num>>>=1;//无符号右移一位
           }
        }
        return Result.ok(count);
    }

    @Override
    public Result logout(HttpServletRequest req) {
        //1.获取当前登陆的jwt
        String jwt = req.getHeader("authorization");
        //2.把当前登陆的jwt放入无效jwt集合，设置有效期为jwt的有效期
        long expire=0L;
        try {
            expire=JwtUtil.getJwtExpire(jwt);
        } catch (UnsupportedEncodingException e) {
            return Result.fail("出现编码问题");
        }
        if(expire>0L){
            RedisIdWorker redisIdWorker = new RedisIdWorker(stringRedisTemplate);
            stringRedisTemplate.opsForValue().set(INVALID_JWT_KEY+jwt,"0",expire,TimeUnit.SECONDS);
        }
        return Result.ok("已退出登陆");
    }

    private User createUserWithPhone(String phone) {
        //1.创建用户
        User user=new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX+RandomUtil.randomString(10));
        //2.保存用户
        save(user);
        return user;
    }
}
